package IT.Demo.Service.impl;

import IT.Demo.Mapper.BrandMapper;
import IT.Demo.Pojo.Brand;
import IT.Demo.Pojo.Pagebean;
import IT.Demo.Service.Brandservice;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import IT.Demo.Util.SqlSessionFactoryUtils;

import java.util.List;


public class Brandserviceimpl implements Brandservice {

    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    @Override
    public List<Brand> selectAll() {


        SqlSession sqlSession = factory.openSession();

        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        List<Brand> brands = mapper.selectAll();

        sqlSession.close();

        return brands;
    }

    @Override
    public void add(Brand brand) {
        SqlSession sqlSession = factory.openSession();

        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        mapper.add(brand);

        sqlSession.commit();

        sqlSession.close();

    }

    @Override
    public void deletByids(int[] ids) {
        SqlSession sqlSession = factory.openSession();

        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        mapper.deleteByids(ids);

        sqlSession.commit();

        sqlSession.close();
    }

    @Override
    public Pagebean<Brand> selectedByPage(int currentPage, int pageSize) {

        SqlSession sqlSession = factory.openSession();

        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        int begin = (currentPage-1) * pageSize;//开始索引

        int size=pageSize;//每页展示条数

        List<Brand> rows = mapper.seletedByPage(begin,size);//返回集合类型的数组

        int totalCount = mapper.totalCount();//返回总记录数

        Pagebean<Brand> pagebean = new Pagebean<>();

        pagebean.setRows(rows);
        pagebean.setTotalCount(totalCount);

        sqlSession.close();

        return pagebean;
    }

    @Override
    public Pagebean<Brand> selectBypageAndcondition(int currentPage, int pageSize, Brand brand) {

        SqlSession sqlSession = factory.openSession();

        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        int begin = (currentPage-1) * pageSize;//开始索引

        int size=pageSize;//每页展示条数

        String brand_name = brand.getBrand_name();
        if(brand_name != null && brand_name.length()>0){
            brand.setBrand_name("%"+brand_name+"%");
        }

        String company_name = brand.getCompany_name();
        if(company_name != null && company_name.length()>0){
            brand.setCompany_name("%"+company_name+"%");
        }

        List<Brand> rows = mapper.selectBypageAndCondition(begin,size,brand);
        int totalcount = mapper.selectCountBypage(brand);

        Pagebean<Brand> pagebean = new Pagebean<>();

        pagebean.setRows(rows);
        pagebean.setTotalCount(totalcount);

        sqlSession.close();

        return pagebean;




    }

}
